package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.LikesBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户点赞service
 */
@Slf4j
@Service
public class LikesBehaviorServiceImpl implements LikesBehaviorService {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 用户对文章进行点赞
     *
     * @param dto
     * @return
     */
    @Override

    public ResponseResult like(LikesBehaviorDto dto) {
        //1.入参校验
        if (dto == null || dto.getArticleId() == null ||
                (dto.getOperation() != 0 && dto.getOperation() != 1) ||
                (dto.getType() != 0 && dto.getType() != 1 && dto.getType() != 2)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断用户是否登录   ThreadLocal中获取用户信息
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.保存数据 ,先根据key查看redis中该用户是否对该文章进行点赞,如果redis中已存在,则无需操作
        //如果redis中没有该用户对该文章的相关点赞操作,则向redis中插入数据,同时更新app端文章微服务中ap_article表的字段
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
        mess.setArticleId(dto.getArticleId());

        if (dto.getOperation() == 0) {//点赞
            //  键:likes_behavior  值是哈希: 键user_id  值 JSON.toJSONString(dto)
            Object value = cacheService.hGet(BehaviorConstants.LIKES_BEHAVIOR + dto.getArticleId(),
                    user.getId().toString());
            if (value != null) {
                //说明该用户对该文章已经进过了点赞
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "该用户已经对该文章进行过点赞操作!");
            }
            //存入redis ,更新数据库ap_article表中该文章的点赞数
            cacheService.hPut(BehaviorConstants.LIKES_BEHAVIOR + dto.getArticleId(),
                    user.getId().toString(),
                    JSON.toJSONString(dto));
//            // TODO 向kafka发送一条消息,由app文章微服务来拉取消费,更新db表 ap_article
//            //发送参数: 文章id ,type : likes/cancel_likes  ,count:1
//            Map map = new HashMap();
//            map.put("articleId", dto.getArticleId());
//            map.put("type", "likes");
//            map.put("count", 1);
//            kafkaTemplate.send(BehaviorConstants.USER_BEHAVIOR_TOPIC, JSON.toJSONString(map));

            //点赞 ;正向操作
            mess.setAdd(1);

        } else {//取消点赞,根据键删除redis中的记录,同时更新数据库ap_article表中该文章的点赞记录数

            cacheService.hDelete(BehaviorConstants.LIKES_BEHAVIOR + dto.getArticleId(),
                    user.getId().toString());
//            //TODO 发送kafka消息,app端文章微服务来进行消费,更新db
//            Map map = new HashMap();
//            map.put("articleId", dto.getArticleId());
//            map.put("type", "cancel_likes");
//            map.put("count", 1);
//            kafkaTemplate.send(BehaviorConstants.USER_BEHAVIOR_TOPIC, JSON.toJSONString(map));
            //取消点赞  :负向操作
            mess.setAdd(-1);
        }
        ////发送kafka消息用于文章分值实时流式计算
        log.info("点赞行为-发送kafka消息用于流式计算...");
        //发送的消息{"articleId":"12345","type":"COLLECTION","add":"1"}
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
